package com.fled.itsmbigscreen.utils;

import java.io.UnsupportedEncodingException;

public class StringToHexConverter {
    public static String convertToHex(String str) {
        StringBuilder hexString = new StringBuilder();

        try {
            // 将字符串转换为字节数组
            byte[] bytes = new byte[0];
                bytes = str.getBytes("UTF-8");

            // 将每个字节转换为十六进制字符串
            for (byte b : bytes) {
                String hex = Integer.toHexString(b & 0xFF).toUpperCase();
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return hexString.toString();
    }


    public static String bytesToHexString(byte... src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    public static void main(String[] args) {
        String str = "Hello, World!";
        String hex = convertToHex(str);
        System.out.println(hex); // 输出：48656C6C6F2C20576F726C6421
    }
}
